/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package provider.impl.coalescent.data;

import coalescent.data.K69Data;
import coalescent.model.K69;
import coalescent.provider.Providers;
import commons.provider.impl.BaseXMLFileBasedProviderImpl;
import org.dom4j.Element;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;

/**
 * An XML based implementation of provider for {@code K69Data}.
 *
 * @version 1.4.0
 * @since 1.0.0
 * @author Susanta Tewari
 * @history First created on Jul 30, 2011
 */
public final class K69XMLDataProviderImpl extends BaseXMLFileBasedProviderImpl<K69Data>
        implements Providers.K69DataProviderFileBased {

    @Override
    protected K69Data toValue(final Element root) throws Exception {


        // mutations
        List<String> mutations = Arrays.asList(root.elementText("mutation").trim().split("-"));
        final int m_count      = mutations.size();
        double theta           = Double.valueOf(root.elementText("theta"));


        // alleles
        final List<Element> alleles           = root.elements("allele");
        final Set<String> alleleLabels        = newHashSet();
        final Map<String, String> alleleSeq   = newHashMap();
        final Map<String, Integer> alleleFreq = newHashMap();

        for (final Element allele : alleles) {

            final String label = allele.attributeValue("label");
            final String seq   = allele.elementText("sequence");
            final Integer freq = Integer.valueOf(allele.elementText("frequency"));

            throw_pEx(seq.length() != m_count, "Site-Count mismatch for allele " + label);
            alleleLabels.add(label);
            alleleSeq.put(label, seq);
            alleleFreq.put(label, freq);
        }


        // data
        return new K69Data(theta, alleleLabels, alleleSeq, alleleFreq, mutations);
    }

    @Override
    public Class<K69> getModelClass() {
        return K69.class;
    }

    @Override
    public Class<K69Data> getDataClass() {
        return K69Data.class;
    }
}
